from flask import Flask
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_migrate import Migrate
from app.database import db
from app.models import User


app = Flask(__name__, static_folder="../static", static_url_path="/")
app.config.from_object('app.config.Config')

# 初始化插件
db.init_app(app)
bcrypt = Bcrypt(app)
CORS(app)
jwt = JWTManager(app)
migrate = Migrate(app, db)  # 初始化 Migrate 扩展

# 标志位，确保只初始化一次
initialized = False

@app.before_request
def create_default_user():
    global initialized
    # 确保只有第一次请求时创建用户
    if not initialized:
        if not User.query.filter_by(email='admin@example.com').first():
            # 如果没有，创建一个管理员用户
            hashed_password = bcrypt.generate_password_hash("123456").decode('utf-8')
            admin_user = User(username="admin", email="admin@example.com", password=hashed_password)
            db.session.add(admin_user)
            db.session.commit()
        initialized = True

from app.routes import *

if __name__ == "__main__":
    app.run()
